import { ref } from 'vue'

export default function useWebSocket(handleMessage, user) {
    const ws = new WebSocket(import.meta.env.VITE_WS_BASE_URL + '/sys/ws');

    const isConnected = ref(false)

    const init = () => {
        ws.onopen = () => {
            // isConnected.value = true;
            bindEvent()
        }
    }

    function bindEvent() {
        ws.addEventListener('open', (event) => {
            console.log('open: ', event)
        }, false)
        ws.addEventListener('message', (event) => {
            handleMessage(event)
        }, false)
        ws.addEventListener('close', (event) => {
            isConnected.value = false;
            console.log('close: ', event)
        }, false)
        ws.addEventListener('error', (event) => {
            console.log('error: ', event)
        }, false)
    }
    init()
    
    return ws

}